package com.baidu.roomdemo.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.baidu.roomdemo.db.Repository
import com.baidu.roomdemo.db.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 管理数据
 * 接收View传递的方法 去处理
 */
class MainViewModel(application: Application):AndroidViewModel(application) {
    //数据仓库
    val repository = Repository(application)
    //保存数据
    val userList = repository.loadUsers()

    fun saveUser(user: User) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.saveUser(user)
        }
    }

    fun deleteUser(user: User) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteUser(user)
        }
    }

    fun deleteAll(){
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteAll()
        }
    }

    fun updateUser(user: User) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateUser(user)
        }
    }
}








